#include"stdio_.h"
FILE_* fopen_(const char* filename,const char* mode){
	size_t fileno = 0;
	size_t filemode = 0666;
	if(!strcmp(mode,"r")){
		fileno = open(filename, O_RDONLY);
	} 
	else if(!strcmp(mode,"w")){
		fileno = open(filename,O_WRONLY |  O_CREAT | O_TRUNC ,filemode);	
	} 
	else if(!strcmp(mode,"a")){
		fileno = open(filename,O_WRONLY |  O_CREAT |  O_APPEND, filemode);
	}
	else{
		printf("open mode error!!!\n");
		return NULL;
	}
	if(fileno <  0){
		printf("open error!!!\n");
		return NULL;
	}
	FILE_* filepoint = (FILE_*)malloc(sizeof(FILE_));
	if(!filepoint){
		perror("filepoint malloc error!!!\n");
		return NULL; 
	}
	filepoint->_flags = LINE_BUFFER;
	filepoint->_fileno = fileno;
	filepoint->_size = 0;
	memset(filepoint->_buffer,0,SIZE);
	return filepoint;
}
void fwrite_(const void* buffer, size_t size,FILE_* stream){
	memcpy(stream->_buffer + stream->_size,buffer,size);
	stream->_size +=size;
	if(stream->_flags == NOT_BUFFER){
		write(stream->_fileno, stream->_buffer,stream->_size);
		stream->_size = 0;
	} 
	if(stream->_flags == LINE_BUFFER && stream->_buffer[size-1] == '\n'){
		write(stream->_fileno,stream->_buffer,stream->_size);
		stream->_size = 0;
	}
	if(stream->_flags == FULLY_BUFFER && stream->_size >= BUFFER_BETY){
		write(stream->_fileno,stream->_buffer,stream->_size);
		stream->_size = 0;
	}
}
void fflush_(FILE_* stream){
	if(stream->_size > 0 ){
	write(stream->_fileno,stream->_buffer,stream->_size);	//write();  Write to kernel buffer
	fsync(stream->_fileno); //Force refresh from kernel buffer to peripheral	
	stream->_size = 0;
	}
}

void fclose_(FILE_* stream){
	fflush_(stream);
	close(stream->_fileno);
	free(stream);
}
